package com.mrx.commons.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import javax.annotation.PostConstruct;

/**
 * @author : Mr.X
 * @since : 2022-12-09 09:34
 **/
@Configuration
public class FakeRedisConfig {

    private static final Logger logger = LoggerFactory.getLogger(FakeRedisConfig.class);

    @PostConstruct
    public void init() {
        logger.info("使用 Fake Redis 替换全局 RedisTemplate");
    }

    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory, ApplicationEventPublisher publisher) {
//        logger.debug("redisTemplate.profile: {}", profile);
//        RedisTemplate<Object, Object> template = "dev".equals(profile) ? FakeRedisTemplate.getInstance(publisher) : new RedisTemplate<>();
        RedisTemplate<Object, Object> template = FakeRedisTemplate.getInstance(publisher);
        template.setConnectionFactory(connectionFactory);
        FastJson2RedisSerializer serializer = new FastJson2RedisSerializer();
        // 使用 StringRedisSerializer 来序列化和反序列化 redis 的 key 值
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(serializer);
        // Hash 的 key 也采用 StringRedisSerializer 的序列化方式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(serializer);
        template.afterPropertiesSet();
        return template;
    }

    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory factory) {
        RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer();
        redisMessageListenerContainer.setConnectionFactory(factory);
        return redisMessageListenerContainer;
    }

}
